<template>
  <div class="user-menu" ref="menuRef">
    <button class="user-btn" @click="isOpen = !isOpen">
      <span class="user-icon">👤</span>
      <span class="user-name">账号</span>
    </button>
    <div class="user-dropdown" :class="{ show: isOpen }">
      <div class="dropdown-header">
        <span class="user-icon">👤</span>
        <div>
          <div class="dropdown-username">用户名称</div>
          <div class="dropdown-email">user@example.com</div>
        </div>
      </div>
      <div class="dropdown-divider"></div>
      <a href="#" class="dropdown-item" @click.prevent="handleItemClick('profile')">个人资料</a>
      <a href="#" class="dropdown-item" @click.prevent="handleItemClick('logout')">退出登录</a>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const emit = defineEmits(['open-profile']);

const isOpen = ref(false);
const menuRef = ref(null);

const handleItemClick = (action) => {
  if (action === 'profile') {
    emit('open-profile');
  } else if (action === 'logout') {
    alert('您已退出登录');
  }
  isOpen.value = false;
};

const handleClickOutside = (event) => {
  if (menuRef.value && !menuRef.value.contains(event.target)) {
    isOpen.value = false;
  }
};

onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>